<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="车牌" prop="carNum">
        <el-input
          v-model="queryParams.carNum"
          placeholder="请输入车牌"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="修车厂" prop="garageId">
        <el-select
          v-model="queryParams.garageId"
          placeholder="请选择修车厂"
          style="width: 190px"
          size="small"
        >
          <el-option
            v-for="garage in garageOptions"
            :key="garage.garageId"
            :label="garage.garageName"
            :value="parseInt(garage.garageId)"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="报备人" prop="reporter">
        <el-input
          v-model="queryParams.reporter"
          placeholder="请输入维修报备人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item
        label="送修时间范围"
        prop="deliveryRangeDataTime"
        label-width="100px"
      >
        <el-date-picker
          v-model="queryParams.deliveryRangeDataTime"
          :picker-options="pickerOptions"
          size="small"
          style="width: 280px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item
        label="维修完成时间"
        prop="finishRangeDataTime"
        label-width="100px"
      >
        <el-date-picker
          v-model="queryParams.finishRangeDataTime"
          :picker-options="pickerOptions"
          size="small"
          style="width: 280px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['car:maintenance:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['car:maintenance:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['car:maintenance:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['car:maintenance:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="maintenanceList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="left" />
      <el-table-column type="index" label="序号" width="60" align="left" />
      <el-table-column label="车牌" align="left" prop="carNum" />
      <el-table-column label="修车厂" align="left" prop="garageName" />
      <el-table-column label="维修报备人" align="left" prop="reporter" />
      <el-table-column
        label="维修送达时间"
        align="left"
        prop="deliveryTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deliveryTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="维修完成时间"
        align="left"
        prop="finishTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.finishTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总金额" align="left" prop="totalAmount" />

      <el-table-column label="维修信息录入人" align="left" prop="enterBy" />
      <el-table-column
        label="操作"
        align="left"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['car:maintenance:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['car:maintenance:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改维修信息对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1200px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-row>
              <el-col :span="12">
                <el-form-item label="车牌" prop="carId">
                  <el-select
                    v-model="form.carId"
                    placeholder="请选择车辆"
                    style="width: 100%"
                    size="small"
                  >
                    <el-option
                      v-for="car in carOptions"
                      :key="car.carId"
                      :label="car.carNum"
                      :value="parseInt(car.carId)"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="修车厂" prop="garageId">
                  <el-select
                    v-model="form.garageId"
                    placeholder="请选择修车厂"
                    style="width: 100%"
                    size="small"
                    @change="changeGarageId"
                  >
                    <el-option
                      v-for="garage in garageOptions"
                      :key="garage.garageId"
                      :label="garage.garageName"
                      :value="parseInt(garage.garageId)"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="维修报备人" prop="reporter">
                  <el-input
                    v-model="form.reporter"
                    placeholder="请输入维修报备人"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="维修送达时间" prop="deliveryTime">
                  <el-date-picker
                    clearable
                    size="small"
                    v-model="form.deliveryTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择维修送达时间"
                    style="width: 100%"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="维修信息录入人" prop="enterBy">
                  <el-input
                    v-model="form.enterBy"
                    placeholder="请输入维修信息录入人"
                  /> </el-form-item
              ></el-col>
              <el-col :span="12">
                <el-form-item label="维修完成时间" prop="finishTime">
                  <el-date-picker
                    clearable
                    size="small"
                    v-model="form.finishTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择维修完成时间"
                    style="width: 100%"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAddMaintenanceDetail"
                >新增维修项目</el-button
              ></el-row
            >
            <el-row>
              <el-table :data="form.carMaintenanceDetailList">
                <el-table-column
                  type="index"
                  label="序号"
                  width="60"
                  align="left"
                />

                <el-table-column
                  label="项目名称"
                  align="left"
                  prop="itemName"
                />
                <el-table-column label="数量" align="left" prop="itemCount">
                  <template slot-scope="scope">
                    <el-input-number
                      v-model="scope.row.itemCount"
                      controls-position="right"
                      :min="1"
                      style="width: 80px"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="单价" align="left" prop="itemPrice" />
                <el-table-column
                  label="操作"
                  align="left"
                  class-name="small-padding fixed-width"
                >
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                      @click="handleDeleteItem(scope.row)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-row>

            <el-form-item label="总金额" prop="totalAmount">
              {{ totalAmount }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维修单照片" prop="photoList">
              <upload-img-list
                actionUrl="/common/upload"
                :imgUrl.sync="form.photoList"
                width="600px"
                height="400px"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--维修项目选择框-->
    <el-dialog
      title="维修项目选择"
      :visible.sync="itemChooseOpen"
      width="400px"
      append-to-body
    >
      <el-form label-width="120px">
        <el-form-item label="维修项目">
          <el-select
            v-model="garageItemId"
            placeholder="请选择维修项目"
            style="width: 100%"
            size="small"
          >
            <el-option
              v-for="garageItem in garageItemOptions"
              :key="garageItem.itemId"
              :label="garageItem.itemName"
              :value="parseInt(garageItem.itemId)"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="confirmItem"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMaintenance,
  getMaintenance,
  delMaintenance,
  addMaintenance,
  updateMaintenance,
} from "@/api/car/maintenance";
import uploadImgList from "@/views/components/uploadImgList";
import { getGarageCombo } from "@/api/car/garage";
import { getGarageItemCombo } from "@/api/car/garageItem";
import { getCarCombo } from "@/api/base/car";

export default {
  name: "Maintenance",
  components: {
    uploadImgList,
  },
  data() {
    // 时间的校验
    let validateStartTime = (rule, value, callback) => {
      if (value === undefined) {
        callback(new Error("送达时间不能为空"));
      } else {
        if (
          new Date(this.form.deliveryTime).getTime() <= new Date().getTime()
        ) {
          callback();
        } else {
          callback();
        }
      }
    };
    let validateEndTime = (rule, value, callback) => {
      if (value === undefined) {
        callback(new Error("完成时间不能为空"));
      } else {
        if (
          new Date(this.form.deliveryTime).getTime() >=
          new Date(this.form.finishTime).getTime()
        ) {
          callback(new Error("完成时间必须大于送达时间！"));
        } else {
          callback();
        }
      }
    };
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 维修信息表格数据
      maintenanceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      garageOptions: [],
      garageItemOptions: [],
      carOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        carNum: undefined,
        garageId: undefined,
        reporter: undefined,
        deliveryRangeDataTime: [],
        deliveryTimeStart: undefined,
        deliveryTimeEnd: undefined,
        finishRangeDataTime: [],
        finishTimeStart: undefined,
        finishTimeEnd: undefined,
        deliveryTime: undefined,
        finishTime: undefined,
        garageId: undefined,
        enterBy: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        carId: [{ required: true, message: "车辆不能为空", trigger: "change" }],
        reporter: [
          { required: true, message: "维修报备人不能为空", trigger: "blur" },
        ],
        deliveryTime: [
          { required: true, validator: validateStartTime, trigger: "blur" },
        ],
        finishTime: [
          { required: true, validator: validateEndTime, trigger: "blur" },
        ],

        garageId: [
          { required: true, message: "修车厂不能为空", trigger: "change" },
        ],
        enterBy: [
          {
            required: true,
            message: "维修信息录入人不能为空",
            trigger: "blur",
          },
        ],
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      itemChooseOpen: false, //维修项目选择框
      garageItemId: undefined,
    };
  },
  computed: {
    // 计算总金额
    totalAmount: function () {
      let total = 0;
      if (this.form.carMaintenanceDetailList) {
        this.form.carMaintenanceDetailList.forEach((v) => {
          total += v.itemPrice * v.itemCount;
        });
      }

      return total;
    },
  },
  created() {
    this.getGarageSelect();
    this.getCarSelect();
    this.getList();
  },
  methods: {
    /** 查询修车厂下拉树结构 */
    getGarageSelect() {
      getGarageCombo({ enabled: 1 }).then((response) => {
        this.garageOptions = response.data;
      });
    },
    /** 查询车辆下拉树结构 */
    getCarSelect() {
      getCarCombo({ enabled: 1 }).then((response) => {
        this.carOptions = response.data;
      });
    },
    /** 查询维修信息列表 */
    getList() {
      this.loading = true;
      if (
        this.queryParams.deliveryRangeDataTime &&
        this.queryParams.deliveryRangeDataTime.length > 0
      ) {
        this.queryParams.deliveryTimeStart =
          this.queryParams.deliveryRangeDataTime[0];
        this.queryParams.deliveryTimeEnd =
          this.queryParams.deliveryRangeDataTime[1];
      } else {
        this.queryParams.deliveryTimeStart = undefined;
        this.queryParams.deliveryTimeEnd = undefined;
      }
      listMaintenance(this.queryParams).then((response) => {
        this.maintenanceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        maintenanceId: undefined,
        reporter: undefined,
        deliveryTime: undefined,
        finishTime: undefined,
        totalAmount: undefined,
        garageId: undefined,
        enterBy: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        carId: undefined,
        photoList: [],
        carMaintenanceDetailList: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.maintenanceId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加维修信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const maintenanceId = row.maintenanceId || this.ids;
      getMaintenance(maintenanceId).then((response) => {
        this.loading = false;
        response.data.photoList=response.data.photoList?response.data.photoList.split(','):[]
        this.form = response.data;
        this.open = true;
        this.title = "修改维修信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          this.form.carMaintenanceDetailList.forEach((v) => {
            v.amount = v.itemPrice * v.itemCount;
          });
          this.form.totalAmount = this.totalAmount;
          let params = JSON.parse(JSON.stringify(this.form));
          params.photoList = params.photoList.join(",");
          if (this.form.maintenanceId != null) {
            updateMaintenance(params)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addMaintenance(params)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const maintenanceIds = row.maintenanceId || this.ids;
      this.$modal
        .confirm('是否确认删除"' + (row.orderName || "已勾选") + '"的数据项?')
        .then(() => {
          this.loading = true;
          return delMaintenance(maintenanceIds);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "car/maintenance/export",
        {
          ...this.queryParams,
        },
        `maintenance_${new Date().getTime()}.xlsx`
      );
    },
    /**选择修车厂**/
    changeGarageId(value) {
      if (value) {
        getGarageItemCombo({ garageId: value }).then((response) => {
          this.garageItemOptions = response.data;
        });
      } else {
        this.garageOptions = [];
      }
    },
    /** 新增维修项目 */
    handleAddMaintenanceDetail() {
      this.itemChooseOpen = true;
    },
    confirmItem() {
      if (this.garageItemId) {
        let item = this.garageItemOptions.find(
          (v) => v.itemId == this.garageItemId
        );

        this.form.carMaintenanceDetailList.push({
          itemId: item.itemId,
          garageId: item.garageId,
          itemName: item.itemName,
          itemPrice: item.itemPrice,
          itemCount: item.itemCount,
          amount: 0,
        });
        this.itemChooseOpen = false;
        this.garageItemId = null;
      }
    },
    /*删除维修项目*/
    handleDeleteItem(row) {
      this.form.carMaintenanceDetailList.splice(row.index, 1);
    },
  },
};
</script>
